<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/9/23 0023
 * Time: 13:44
 */

namespace App\App\Services;


use App\Models\Activity\Activity;
use App\Models\Activity\ActivityService;
use App\Models\ActivityInfo\ActivityInfo;
use App\Models\ActivityInfo\ActivityInfoService;
use App\Models\ActivityPrize\ActivityPrizeService;
use App\Models\ActivityRecord\ActivityRecordService;
use App\Models\PrizeRecord\PrizeRecord;
use App\Models\PrizeRecord\PrizeRecordService;
use Carbon\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use \App\Models\Prize\PrizeService;

class PrizeStockService
{
    private $activityService;
    private $activityInfoService;
    private $activityPrizeService;
    private $prizeRecordService;
    private $prizeService;
    private $activityRecordService;

    public function __construct(ActivityService $activityService,
                                ActivityInfoService $activityInfoService,
                                ActivityPrizeService $activityPrizeService,
                                PrizeRecordService $prizeRecordService,
                                PrizeService $prizeService,
                                ActivityRecordService $activityRecordService)
    {
        $this->activityService = $activityService;
        $this->activityInfoService = $activityInfoService;
        $this->activityPrizeService = $activityPrizeService;
        $this->prizeRecordService = $prizeRecordService;
        $this->prizeService = $prizeService;
        $this->activityRecordService = $activityRecordService;
    }

    public function stockRecycle()
    {
        //回收活动结束后没用完的奖品
        $activities = $this->activityService->getFinishedActivities();
        foreach ($activities as $key => $activity) {
            //按活动回收奖品
            $this->recycleByActivity($activity);
        }
        //回收没有兑换的奖品
        $activities = $this->activityService->getFinishedActivitiesOneMonthsAgo();
        if(count($activities)) {
            foreach ($activities as $key => $activity) {
                $this->recycleByDate($activity);
            }
        }
        //删除活动后回收没有兑换的奖品
        $activities = $this->activityService->getDeletedActivitiesOneMonthAgo();
        if(count($activities)) {
            foreach ($activities as $key => $activity) {
                $this->recycleByDate($activity);
            }
        }

        echo '--recycle end--';
    }

    /**
     * 回收未兑换的奖品
     * @param Activity $activity
     */
    public function recycleByDate(Activity $activity){
        $recycleIds = $prizes = [];
        $activity_records = $activity->records;
        DB::beginTransaction();
        try {
            if ($activity_records) {
                foreach ($activity_records as $item) {
                    if ($item->is_exchange == ActivityInfo::IS_EXCHANGE_NO && $item->is_recycle == 0) {
                        if (empty($prizes[$item->prize_id])) {
                            $prizes[$item->prize_id] = $item->number;
                        } else {
                            $prizes[$item->prize_id] += $item->number;
                        }
                        //已经回收的id
                        array_push($recycleIds, $item->id);
                    }
                }
                if ($prizes) {
                    Log::info('回收没有兑换的奖品数据：', $prizes);
                    foreach ($prizes as $prize_id => $number) {
                        $this->addPrizeRecord($number, $prize_id);
                    }
                }
                $activity_prize_params = [
                    'is_recycle' => 1,
                    'recycle_time' => Carbon::now(),
                ];
                if ($recycleIds) {
                    Log::info('month recycle:', $recycleIds);
                    $this->activityRecordService->updateRecords($activity_prize_params, $recycleIds);
                }
            }
            DB::commit();
            return true;
        }catch (\Exception $e){
            DB::rollback();
            Log::info($e->getMessage());
            return false;
        }
    }

    /**
     * 奖品回收
     * @param $number
     * @param $prize_id
     */
    public function addPrizeRecord($number,$prize_id)
    {
        Log::info("recycle_num:".$number."prize_id:".$prize_id);
        $prizeRecords = $this->prizeRecordService->getByConditions(array('prize_id' => $prize_id));
        if($prizeRecords) {
            $prizeRecords = $prizeRecords->toArray();
            $prizeRecordSummary = array_column($prizeRecords, 'summary', 'updated_at');
            ksort($prizeRecordSummary);
            $availableNumber = end($prizeRecordSummary);
            $prizeRecord = array(
                'prize_id' => $prize_id,
                'number' => $number,
                'summary' => $availableNumber + $number,
                'operate' => PrizeRecord::RECYCLE,
                'created_at' => date('Y-m-d H:i:s')
            );
            Log::info($prizeRecord);
            $result = $this->prizeRecordService->create($prizeRecord);
        } else {
            Log::info('--prize null--');
            echo '--prize null--';
        }
    }

    /**
     * 按活动回收奖品
     * @param Activity $activity
     */
    public function recycleByActivity(Activity $activity)
    {
        $activity_prizes = $activity->prizes;
        if ($activity_prizes) {
            $activity_prizes = $activity_prizes->toArray();
            foreach ($activity_prizes as $key => $activity_prize) {
                $prize_info = $this->prizeService->getPrizeById($activity_prize['prize_id']);
                if (empty($prize_info) || $activity_prize['is_recycle'] == 1) {
                    continue;
                }
                //实物类
                if (in_array($prize_info['type_code'], ['coupon', 'entity'])) {
                    Log::info('recycle num:' . $activity_prize['surplus'] . ' prize_id:' . $activity_prize['prize_id']);
                    DB::beginTransaction();
                    try {
                        $this->addPrizeRecord($activity_prize['surplus'], $activity_prize['prize_id']);
                        $activity_prize_params = [
                            'is_recycle' => 1,
                        ];
                        $conditions = [
                            'activity_id' => $activity_prize['activity_id'],
                            'prize_id' => $activity_prize['prize_id']
                        ];
                        //更新库存回收状态
                        $this->activityPrizeService->update($activity_prize_params, $conditions);
                        DB::commit();
                        return true;
                    } catch (\Exception $e) {
                        DB::rollback();
                        Log::info($e->getMessage());
                        return false;
                    }
                }
            }
        }
    }

}